# translation helpers
XLATE_DOMAIN = "DDBug"

import zLOG

from Products.PageTemplates.GlobalTranslationService import getGlobalTranslationService
from TAL.TALInterpreter import interpolate, normalize

class TranslationError(Exception):
    pass

_dbgmsg = """translating to %r: %r -> %r
Translation Service: %r
------
"""

def _translate(msgid, mapping=None,
               context=None, target_language=None):
    xlationService = getGlobalTranslationService()
    translate = xlationService.translate
    translation = translate(domain=XLATE_DOMAIN,
                            msgid=msgid,
                            mapping=mapping,
                            context=context,
                            target_language=target_language)
    zLOG.LOG("DDBug._translate()", zLOG.BLATHER, "translating",
             _dbgmsg % (target_language, msgid, translation, xlationService))
    return translation

def xlate(context=None, msgid=None, text=None,
          mapping=None, target_language=None):
    # why put the context first? because whe can use this as a
    # method and it will bind automagically to self in instances.

    # this algorithm is taken from how I understand TAL handles i18n
    # take a look at TAL.TALInterpreter to see the mess...
    if msgid is None:
        if text is None:
            # both are none! argh!
            raise TranslationError("msgid and text can't both be None")
        msgid = normalize(text)
    xlation = _translate(msgid=msgid,
                         mapping=mapping,
                         context=context,
                         target_language=target_language)
    if xlation is not None:
        return xlation
    # we got no translation
    if text is not None:
        # return text untranslated
        return interpolate(text, mapping)
    # we haven't got text, but we know msgid is valid
    return "No translation for msgid: [%s]" % msgid
